package com.lhgray.sglhome.presentation.viewModel

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.Typeface
import android.net.Uri
import androidx.exifinterface.media.ExifInterface
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lhgray.sglhome.common.utlis.WatermarkUtils
import com.lhgray.sglhome.domain.usecase.UploadPhotoUseCase
import com.lhgray.sglhome.domain.model.ImageBean
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import javax.inject.Inject

/**
 * 作者：lhgray on 2025/3/31.
 * 邮箱：lhgray@163.com
 * 文件：com.lhgray.sglhome.screen
 */
@HiltViewModel
class UploadPhotoViewModel @Inject constructor(private val uploadPhotoUseCase: UploadPhotoUseCase) :
    ViewModel() {
    private var sourceTable: String? = ""
    private var sourceId: String? = ""
    private var longitude: String? = ""
    private var latitude: String? = ""

    // 创建一个 MutableLiveData 对象，用于存储数据
    private val _data = MutableLiveData<Boolean>()

    // 对外暴露一个只读的 LiveData 对象
    val data: LiveData<Boolean> = _data

    fun savePhoto(items: List<ImageBean>?, editSubject: String, editDetail: String) {
        viewModelScope.launch {
            val uploadPhoto = uploadPhotoUseCase.invoke(
                items?.map { it.imageUri },
                sourceTable ?: "",
                sourceId ?: "",
                editSubject,
                editDetail
            )
            _data.value = uploadPhoto.isSuccess
        }
    }

    fun addWatermarkToImage(context: Context, uri: Uri) = flow {
        val correctlyOrientedImage = getCorrectlyOrientedImage(context, uri)
        val bitmap = correctlyOrientedImage?.let { bitmaps ->

            val list = mutableListOf(
                SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date())
            )
            if (longitude?.isNotEmpty() == true) list.add("LON = $longitude")
            if (latitude?.isNotEmpty() == true) list.add("LAT = $latitude")
            WatermarkUtils.addCornerWatermarks(bitmaps, list, 65f)
        }
        val bitmapOutputStream = context.contentResolver.openOutputStream(uri)
        bitmapOutputStream?.use {
            bitmap?.compress(Bitmap.CompressFormat.JPEG, 90, bitmapOutputStream)
            bitmap?.recycle()
            emit(uri)
        }
    }

    private fun addWatermark(
        originalBitmap: Bitmap,
        texts: List<String>,
        textColor: Int = Color.BLACK,
        textSize: Float = 40f,
        alpha: Int = 150,
        paddingRight: Int = 50,
        paddingBottom: Int = 50
    ): Bitmap {
        val resultBitmap = originalBitmap.copy(Bitmap.Config.ARGB_8888, true)
        val canvas = Canvas(resultBitmap)
        val paint = Paint().also {
            it.color = textColor
            it.textSize = textSize
            it.isAntiAlias = true
            it.alpha = alpha // 设置透明度（0-255）
            it.typeface = Typeface.DEFAULT_BOLD
        }

        // 计算水印位置（右下角）
        val textHeight = paint.descent() - paint.ascent()
        var yPos = originalBitmap.height - paddingBottom

        texts.reversed().forEach { text ->
            val textWidth = paint.measureText(text)
            val xPos = originalBitmap.width - textWidth - paddingRight
            yPos -= textHeight.toInt() // 向上偏移行高
            canvas.drawText(text, xPos.toFloat(), yPos.toFloat(), paint)
        }

        return resultBitmap
    }

    private fun getCorrectlyOrientedImage(context: Context, uri: Uri): Bitmap? {
        val inputStream = context.contentResolver.openInputStream(uri)
        inputStream?.use {
            val options = BitmapFactory.Options()
            options.inPreferredConfig = Bitmap.Config.ARGB_8888
            val bitmap = BitmapFactory.decodeStream(inputStream, null, options)
            val exif = ExifInterface(inputStream)
            val orientation = exif.getAttributeInt(
                ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_UNDEFINED
            )
            return when (orientation) {
                ExifInterface.ORIENTATION_ROTATE_90 -> rotateBitmap(bitmap, 90f)
                ExifInterface.ORIENTATION_ROTATE_180 -> rotateBitmap(bitmap, 180f)
                ExifInterface.ORIENTATION_ROTATE_270 -> rotateBitmap(bitmap, 270f)
                else -> bitmap
            }
        }
        return null
    }

    private fun rotateBitmap(bitmap: Bitmap?, degrees: Float): Bitmap? {
        bitmap?.let {
            val matrix = Matrix()
            matrix.postRotate(degrees)
            return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
        }
        return null
    }

    fun setSourceData(
        sourceTable: String?,
        sourceId: String?,
        longitude: String,
        latitude: String
    ) {
        this.sourceTable = sourceTable
        this.sourceId = sourceId
        this.longitude = longitude
        this.latitude = latitude
    }
}